package csx.study.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import csx.study.demo.dto.Result;
import csx.study.demo.entity.Shop;
import csx.study.demo.entity.ShopType;
import csx.study.demo.enums.CacheTTL;
import csx.study.demo.mapper.ShopTypeMapper;
import csx.study.demo.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author csx
 * @since 2025-03-03
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PREFIX="cache:shopType:";
    private static final String NULL_MARKER="";

    // 数据不用修改，选String类型
    @Override
    public Result queryTypeList() {
        String key = KEY_PREFIX;

        // 1. 从Redis查询JSON字符串
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2. 不为""且不为null
        if (StrUtil.isNotBlank(json)) {
            List<ShopType> shopTypes = JSONUtil.toList(json, ShopType.class);

            // 2.1 集合为空
            if(shopTypes.isEmpty()){
                return Result.fail("没有店铺类型");
            }

            // 2.2 不为空，返回
            return Result.ok(shopTypes);
        }

        // 3. 为""
        if (NULL_MARKER .equals(json)) {
            return Result.fail("没有店铺类型");
        }

        // 4. 查询数据库
        List<ShopType> shopTypes=query().lambda().orderByAsc(ShopType::getSort).list();

        // 5. 数据库不存在->缓存空值
        if (shopTypes.isEmpty()) {
            stringRedisTemplate.opsForValue().set(key, NULL_MARKER, CacheTTL.NULL.getValue(),CacheTTL.NULL.getUnit());
            return Result.fail("没有店铺类型");
        }

        // 6. 数据库存在->写缓存
        String shopTypeJson = JSONUtil.toJsonStr(shopTypes);
        stringRedisTemplate.opsForValue().set(key, shopTypeJson, CacheTTL.SHOP.getValue(), CacheTTL.SHOP.getUnit());

        return Result.ok(shopTypes);
    }

}
